<template>
  <div>
    <div class="searchbox">
      <input v-model="keyWord" type="text" placeholder="请输入城市名或拼音">
    </div>
    <div class="searchcontent" v-show="keyWord">
      <ul>
        <li v-for="item of list" :key="item.id" @click="handleClickCity(item.name)">{{item.name}}</li>
        <li v-show="showNoneResult">暂无匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'Vuex'
export default {
  name: 'citySearch',
  props: {
    cityList: Object
  },
  data () {
    return {
      keyWord: '',
      list: [],
      timer: null,
      showNoneResult: true
    }
  },
  methods: {
    handleClickCity (city) {
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch: {
    keyWord () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWord) {
        this.list = []
        this.showNoneResult = true
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cityList) {
          this.cityList[i].forEach((value) => {
            if (value.spell.indexOf(this.keyWord) > -1 || value.name.indexOf(this.keyWord) > -1) {
              result.push(value)
              this.showNoneResult = false
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import "~@/assets/style/varible.styl"
  .searchbox
    height .6rem
    padding .13rem
    background $color-blue
    text-align center
    input
      display block
      width 98%
      height .5rem
      /*padding .1rem*/
      font-size .24rem
      color $color-black3
  .searchcontent
    position absolute
    z-index 1
    top 2.06rem
    left 0
    right 0
    bottom 0
    background $color-black2
    ul
      li
        box-sizing border-box
        height .6rem
        padding 0 .1rem
        margin 0 auto
        font-size .24rem
        color $color-black3
        line-height .6rem
        background $color-white
        border-bottom 1px solid $color-black2
</style>
